package com.harmontronics.hanma.paas.paas.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.harmontronics.hanma.paas.paas.domain.organization.service.HmUserExportService;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Service;

@Service("hmUserExportAppService")
@DS("#header.App-Unique")
public class HmUserExportAppService extends HmUserExportService {

    public static final String PATH = "excel"+File.separator + "userimporttemplate.xlsx";

    public static final String FILENAME = "userimporttemplate.xlsx";

    public void downloadExcel(HttpServletRequest request,
            HttpServletResponse response) throws IOException {

            //FileInputStream inputStream = new FileInputStream(pullPath);
            ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resourcePatternResolver.getResources("classpath:"+ PATH);


            response.setContentType(
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.addHeader("Content-Disposition",
                        "attachment;fileName=" + URLEncoder.encode(FILENAME, "UTF-8"));

            try(InputStream inputStream = resources[0].getInputStream();) {
                XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
                OutputStream os = response.getOutputStream();
                //byte[] buffer = new byte[inputStream.available()];
                //inputStream.read(buffer);
                //os.write(buffer);
                workbook.write(os);
                os.flush();
                os.close();
            } catch (Exception io) {
                    io.printStackTrace();
            }
    }

}
